#!/bin/bash

# ================== 配置参数 ==================

# Android NDK 路径
ANDROID_NDK=/path/to/android-ndk-r27b

# 目标架构：arm, arm64, x86, x86_64
ARCH=arm64  # 可选: arm, arm64, x86, x86_64

# API 级别
API=21

# x264 源码路径
X264_SOURCE=$(pwd)

# 输出目录
OUTPUT_DIR=${X264_SOURCE}/android/${ARCH}

# ==================================================

# 设置工具链和目标
case $ARCH in
  arm)
    ANDROID_ABI=armeabi-v7a
    TARGET_HOST=arm-linux-androideabi
    TARGET_CPU=armv7-a
    EXTRA_CFLAGS=""
    ;;
  arm64)
    ANDROID_ABI=arm64-v8a
    TARGET_HOST=aarch64-linux-android
    TARGET_CPU=armv8-a
    EXTRA_CFLAGS=""
    ;;
  x86)
    ANDROID_ABI=x86
    TARGET_HOST=i686-linux-android
    TARGET_CPU=i686
    EXTRA_CFLAGS="-m32"
    ;;
  x86_64)
    ANDROID_ABI=x86_64
    TARGET_HOST=x86_64-linux-android
    TARGET_CPU=x86-64
    EXTRA_CFLAGS=""
    ;;
  *)
    echo "Unsupported ARCH: $ARCH"
    exit 1
    ;;
esac

# 工具链路径
TOOLCHAIN=$ANDROID_NDK/build/cmake/android.toolchain.cmake

# 设置编译器前缀
CC="$ANDROID_NDK/ndk-build NDK_CC=$TARGET_HOST"  # 实际上我们用 configure 的 --cross-prefix

# 使用 NDK 的 sysroot
SYSROOT=$ANDROID_NDK/toolchains/llvm/prebuilt/$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m)/sysroot

# 设置编译器（LLVM）
CC=$ANDROID_NDK/toolchains/llvm/prebuilt/$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m)/bin/$TARGET_HOST$API-clang
CXX=$ANDROID_NDK/toolchains/llvm/prebuilt/$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m)/bin/$TARGET_HOST$API-clang++

# 清理旧构建
make distclean 2>/dev/null || true

# 配置编译选项
./configure \
  --host=$TARGET_HOST \
  --cross-prefix=$ANDROID_NDK/toolchains/llvm/prebuilt/$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m)/bin/$TARGET_HOST- \
  --sysroot=$SYSROOT \
  --prefix=$OUTPUT_DIR \
  --enable-static \
  --disable-shared \
  --enable-pic \
  --disable-asm \
  --disable-cli \
  --disable-thread \
  --disable-opencl \
  --disable-ffms \
  --disable-gpac \
  --disable-lavf \
  --disable-swscale \
  --disable-vp9 \
  --disable-lsmash \
  CC="$CC" \
  CXX="$CXX" \
  AR="$ANDROID_NDK/toolchains/llvm/prebuilt/$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m)/bin/llvm-ar" \
  RANLIB="$ANDROID_NDK/toolchains/llvm/prebuilt/$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m)/bin/llvm-ranlib" \
  STRIP="$ANDROID_NDK/toolchains/llvm/prebuilt/$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m)/bin/$TARGET_HOST-strip" \
  CFLAGS="--target=$TARGET_HOST${API} -I$SYSROOT/usr/include -D__ANDROID_API__=$API $EXTRA_CFLAGS -Os -fPIC" \
  LDFLAGS="--target=$TARGET_HOST${API} -L$SYSROOT/usr/lib/$TARGET_HOST $EXTRA_CFLAGS"

# 编译并安装
make -j$(nproc)
make install

echo "✅ x264 已安装到: $OUTPUT_DIR"